package com.aliyun.mts.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.aliyun.mts.domain.OSSFileDO;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * 阿里云OSS工具类
 * 
 * @author liwb 2015-11-6 上午10:19:41
 */
public class OSSUtil {

    /**
     * 上次文件到OSS
     * 
     * @param filePath
     *            文件路径
     * @param fileName
     *            文件名
     * @return
     */
    public static OSSFileDO uploadLocalFile(String filePath, String fileName) {
        return uploadLocalFile(AliyunConfig.inputBucket,
                AliyunConfig.bucketPath + fileName, filePath);
    }

    /**
     * 上传本地文件到OSS
     * 
     * @param bucket
     * @param object
     *            文件保存地址
     * @param filePath
     *            源文件地址
     * @return
     */
    public static OSSFileDO uploadLocalFile(String bucket, String object,
            String filePath) {
        try {
            File file = new File(filePath);
            InputStream content = new FileInputStream(file);

            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(file.length());
            OSSClientUtil.getOSSClient().putObject(bucket, object, content,
                    meta);

            String encodedObjectName = URLEncoder.encode(object, "utf-8");
            return new OSSFileDO(AliyunConfig.location, bucket,
                    encodedObjectName);
        } catch (Exception e) {
            throw new RuntimeException("fail@uploadLocalFile");
        }
    }

    /**
     * 删除文件
     * 
     * @param bucketName
     * @param key
     */
    public static void deleteObject(String bucketName, String key) {
        // 删除Object
        OSSClientUtil.getOSSClient().deleteObject(bucketName, key);
    }

    /**
     * 获取Bucket下的所有文件
     * 
     * @param bucketName
     */
    public static List<String> listBucket(String bucketName) {
        List<String> url = new ArrayList<String>();

        // 构造ListObjectsRequest请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(
                bucketName);

        // List Objects
        ObjectListing listing = OSSClientUtil.getOSSClient().listObjects(
                listObjectsRequest);

        // 遍历所有Object
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            url.add(objectSummary.getKey());
        }
        return url;
    }

    /**
     * 列出制定目录下的所有文件夹
     * 
     * @param bucketName
     * @param filePath
     */
    public static List<String> listDirectory(String bucketName, String filePath) {

        // 构造ListObjectsRequest请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(
                bucketName);

        // "/" 为文件夹的分隔符
        listObjectsRequest.setDelimiter("/");

        // 列出fun目录下的所有文件和文件夹
        listObjectsRequest.setPrefix(filePath);

        ObjectListing listing = OSSClientUtil.getOSSClient().listObjects(
                listObjectsRequest);
        return listing.getCommonPrefixes();
    }

    /**
     * 列出指定目录下的文件
     * 
     * @param bucketName
     * @param filePath
     */
    public static List<String> listFiles(String bucketName, String filePath) {
        List<String> url = new ArrayList<String>();

        // 构造ListObjectsRequest请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(
                bucketName);

        // "/" 为文件夹的分隔符
        listObjectsRequest.setDelimiter("/");

        // 列出fun目录下的所有文件和文件夹
        listObjectsRequest.setPrefix(filePath);

        ObjectListing listing = OSSClientUtil.getOSSClient().listObjects(
                listObjectsRequest);

        // 遍历所有Object
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            url.add(objectSummary.getKey());
        }
        return url;
    }

    /**
     * 下载Object
     * 
     * @param bucketName
     * @param keys
     * @param destFile
     *            目标文件夹
     * @param replaceStr
     *            用来替换的key段
     */
    public static String downFile(String bucketName, List<String> keys,
            String destFile, String replaceStr) {
        // ObjectMetadata objectMetadata;
        File file;
        String m3u8Name = null;// 要返回的m3u8文件
        for (String key : keys) {
            // 新建GetObjectRequest
            GetObjectRequest getObjectRequest = new GetObjectRequest(
                    bucketName, key);

            if (replaceStr != null) {
                key = key.replace(replaceStr, "");
            }
            file = new File(destFile + key);
            if (key.endsWith(".m3u8")) {
                m3u8Name = key;
            }

            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            // 下载Object到文件
            // objectMetadata =
            OSSClientUtil.getOSSClient().getObject(getObjectRequest, file);

        }
        return m3u8Name;
    }

    public static void main(String[] args) {
        String bucketName = "demo102";
        // listBucket(bucketName);
        String key = "demo/m3u8/";
        // deleteObject(bucketName, key);
        // String filePath = "demo/m3u8/";
        List<String> url = listFiles(bucketName, key);
        // String filePath = "demo/";
        // listDirectory(bucketName, filePath);
        // List<String> list = new ArrayList<String>();
        // list.add(key);
        if (url.size() > 0)
            downFile(bucketName, url,
                    "E:\\apache-tomcat-6.0.43\\webapps\\Ckplayer\\",
                    "demo/m3u8/");
    }
}
